//
//  LoginController.m
//  JF_New_DYKT
//
//  Created by 陈雷 on 2017/8/24.
//  Copyright © 2017年 陈雷. All rights reserved.
//

#import "LoginController.h"
#import "FirstRegisterController.h"
#import "SecondRegisterController.h"
#import "Login_registerModel.h"

@interface LoginController ()<WXApiManagerDelegate,TencentSessionDelegate>

@property (weak, nonatomic) IBOutlet BaseTextfiled *phoneTf;
@property (weak, nonatomic) IBOutlet BaseTextfiled *psdTf;

@property (weak, nonatomic) IBOutlet UIButton *wxBtn;
@property (nonatomic,strong) Login_registerModel *login_Model;

@property (nonatomic,strong) TencentOAuth *tencentOAuth;

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.phoneTf.keyboardType = UIKeyboardTypeNumberPad;
    self.psdTf.keyboardType = UIKeyboardTypeASCIICapable;
    [self.phoneTf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.psdTf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(swapAction) name:@"dismissAction" object:nil];
    
    self.wxBtn.hidden = ![WXApi isWXAppInstalled];
    [JFCrazyTool shareManager].delegate = self;
    
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_APPID andDelegate:self];
}

- (void)swapAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"dismissAction" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
}


- (IBAction)handleAction:(UIButton *)sender {
    
    [self.phoneTf resignFirstResponder];
    [self.psdTf resignFirstResponder];
    
    if (sender.tag == 100) {
        NSLog(@"手机号登录");
        [self loginByPhoneNum];
        
    }else if (sender.tag == 200){
        NSLog(@"手机号注册");
        
        FirstRegisterController *firstVc = [[FirstRegisterController alloc]init];
        BaseNavController *registerNav = [[BaseNavController alloc]initWithRootViewController:firstVc];
        [self presentViewController:registerNav animated:YES completion:nil];
        
    }else if (sender.tag == 300){
        NSLog(@"忘记密码");
        
        SecondRegisterController *firstVc = [[SecondRegisterController alloc]init];
        firstVc.fromWhere = @"forgetPsd";
        BaseNavController *registerNav = [[BaseNavController alloc]initWithRootViewController:firstVc];
        [self presentViewController:registerNav animated:YES completion:nil];
        
    }else if (sender.tag == 400){
        NSLog(@"微信登录");
        
        SendAuthReq *req = [[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo";
        req.state = @"com.xgkj.dykt";
        [WXApi sendReq:req];
        
        
    }else if (sender.tag == 500){
        NSLog(@"QQ登录");
        
        self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQ_APPID andDelegate:self];
        NSArray *permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,kOPEN_PERMISSION_GET_OTHER_INFO, nil];
        [self.tencentOAuth authorize:permissions inSafari:NO];

    }
    
    
}

- (IBAction)showPsdStyle:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    NSLog(@"密码样式");
    
    self.psdTf.secureTextEntry = !sender.selected;
    
}


#pragma mark- 接收微信回调
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response{
    //    NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
    //    NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", response.code, response.state, response.errCode];
    if (response.errCode == -2) {
        
        [JKToast showWithText:@"用户取消"];
    }else if(response.errCode == 0){
        NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WX_APPID,WX_AppSecret,response.code];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *tokenUrl = [NSURL URLWithString:url];
            NSString *tokenStringData = [NSString stringWithContentsOfURL:tokenUrl encoding:NSUTF8StringEncoding error:nil];
            NSData *data = [tokenStringData dataUsingEncoding:NSUTF8StringEncoding];
            dispatch_async(dispatch_get_main_queue(), ^{
                if(data){
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSString *token = [dic objectForKey:@"access_token"];
                    NSString *openId = [dic objectForKey:@"openid"];
                    
                    [self ifHaveRegister:token openid:openId thirdType:@"1"];
                    
                }
            });
        });
    }
}


- (void)ifHaveRegister:(NSString *)token openid:(NSString *)openid thirdType:(NSString *)thirdType{
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/User/thirdLogin",kDomainName];
    
    NSDictionary *paramDic = @{@"thirdId":[openid lowercaseString],
                               @"thirdType":thirdType};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    [request post:urlStr params:paramDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {
            
            NSString *userId = responseObject[@"data"][@"UID"];
            [UserDefaults setObject:userId forKey:@"UID"];
            [self dismissViewControllerAnimated:YES completion:nil];
           [JKToast showWithText:@"登录成功"];
            
        }else if([responseObject[@"code"] isEqualToString:@"2"]){
            [self getWxUserInfo:token openid:openid thirdType:@"1"];
        }else{
        
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    

}

-(void)getWxUserInfo:(NSString *)token openid:(NSString *)openid thirdType:(NSString *)thirdType{
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

                NSString *nickname = [dic objectForKey:@"nickname"];
                NSString *headUrl = [dic objectForKey:@"headimgurl"];
                NSString *openId = [dic objectForKey:@"openid"];
                
                NSString *sex = nil;
                if ([dic[@"sex"] intValue] == 1) {
                    sex = @"1";
                }else{
                    sex = @"0";
                }
                
                [self doThirdLogin:[openId lowercaseString] nick:nickname logo:headUrl sexStr:sex thirdType:thirdType];
            }
        });
        
    });
}


- (void)doThirdLogin:(NSString *)openId nick:(NSString *)nickName logo:(NSString *)headLogo sexStr:sex thirdType:(NSString *)thirdType{
    
    //微信
    FirstRegisterController *firstVc = [[FirstRegisterController alloc]init];
    
    if ([thirdType isEqualToString:@"1"]) {
        firstVc.fromWhere = @"wx";
    }else if ([thirdType isEqualToString:@"2"]){
        firstVc.fromWhere = @"qq";
    }
    
    BaseNavController *registerNav = [[BaseNavController alloc]initWithRootViewController:firstVc];
    
    self.login_Model = [[Login_registerModel alloc]init];
    
    self.login_Model.image_base64 = headLogo;
    
    self.login_Model.nickname = nickName;
    
    self.login_Model.sex = sex;
    
    self.login_Model.open_id = openId;
    
    self.login_Model.third_type = thirdType;
    
    firstVc.login_registerModel = self.login_Model;
    
    [self presentViewController:registerNav animated:YES completion:nil];

}

#pragma mark- 获取QQ用户信息
- (void)tencentDidLogin
{
    //    NSLog(@"%@",self.tencentOAuth.openId);
    [self.tencentOAuth getUserInfo];
}

- (void)getUserInfoResponse:(APIResponse*) response{
    if(response.retCode ==URLREQUEST_SUCCEED && response.detailRetCode ==kOpenSDKErrorSuccess){
        //        NSLog(@"%@",response.jsonResponse);
        NSString *openId = self.tencentOAuth.openId;
        NSString *nickname = [response.jsonResponse objectForKey:@"nickname"];
        NSString *headUrl = [response.jsonResponse objectForKey:@"figureurl_qq_2"];
        NSString *sexStr = [response.jsonResponse objectForKey:@"gender"];
        NSString *sex = nil;
        if ([sexStr isEqualToString:@"女"]) {
            sex = @"0";
        }else{
            sex = @"1";
        }
        
        [self ifHaveRegisterOpenid:[openId lowercaseString] thirdType:@"2" nick:nickname logo:headUrl sexStr:sex];
    }
}


-(void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
        [JKToast showWithText:@"用户取消登录"];
    }else{
        [JKToast showWithText:@"登录失败"];
    }
}
-(void)tencentDidNotNetWork{
    
    [JKToast showWithText:@"没有网络了,登录失败"];
}

#pragma mark- 判断QQ是否已经注册过
- (void)ifHaveRegisterOpenid:(NSString *)openid thirdType:(NSString *)thirdType nick:(NSString *)nickName logo:(NSString *)headLogo sexStr:sex{
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/User/thirdLogin",kDomainName];
    
    NSDictionary *paramDic = @{@"thirdId":[openid lowercaseString],
                               @"thirdType":thirdType};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    [request post:urlStr params:paramDic success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {
            
            NSString *userId = responseObject[@"data"][@"UID"];
            
            [UserDefaults setObject:userId forKey:@"UID"];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
           [JKToast showWithText:@"登录成功"];
            
        }else if([responseObject[@"code"] isEqualToString:@"2"]){
            
            [self doThirdLogin:openid nick:nickName logo:headLogo sexStr:sex thirdType:thirdType];
        }else{
            
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

#pragma mark- 手机号登录
- (void)loginByPhoneNum{

    if (self.phoneTf.text.length <= 0 || self.psdTf.text.length <= 0) {
        
        [JKToast showWithText:@"请输入您的手机号以及密码"];
        return;
    }
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/User/userLogin",kDomainName];
    
    NSString *psdStr = [JFCrazyTool md5:self.psdTf.text];
    
    NSDictionary *paramDic = @{@"mobile":self.phoneTf.text,
                               @"password":psdStr};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    [request post:urlStr params:paramDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {

            NSString *userId = responseObject[@"data"][@"UID"];
            [UserDefaults setObject:userId forKey:@"UID"];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
           [JKToast showWithText:@"登录成功"];
        }else{
            
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

}


@end
